const app = getApp()

Component({
  properties: {
    roomId: {
      type: String,
      value: ''
    },
    roomStatus: {
      type: Number
    },
    word: {
      type: String
    }
  },
  data: {
    inputValue: '',
    msgWatcher: null,
    msgList: []
  },
  observers: {
    roomId (roomId) {
      roomId && !this.msgWatcher && this.initWatchMsg()
    }
  },
  lifetimes: {
    detached() {
      this.data.msgWatcher.close()
    },
  },
  methods: {
    handleInput(e) {
      this.setData({
        inputValue: e.detail.value
      })
    },
    sendMsg() {
      const { inputValue } = this.data
      if (!inputValue) {
        wx.showToast({
          title: '不能发送空消息',
          icon: 'none',
          duration: 2000
        })
        return
      }
      wx.cloud.callFunction({
        name: 'drawsthFunctions',
        data: {
          url: 'message/add',
          data: {
            roomId: this.data.roomId,
            roomStatus: this.data.roomStatus,
            content: inputValue,
            senderName: app.globalData.userInfo.nickName
          }
        }
      }).then(res => {
        this.setData({
          inputValue: ''
        })
      })
    },
    initWatchMsg() {
      const db = wx.cloud.database()
      const msgWatcher = db.collection('message').orderBy('time', 'asc').where({
        roomId: this.data.roomId,
        roomStatus: this.data.roomStatus
      }).watch({
        onChange: (snapshot) => {
          // console.log('snapshot', snapshot)
          // console.log('docs\'s changed events', snapshot.docChanges)
          // console.log('query result snapshot after the event', snapshot.docs)
          // console.log('is init data', snapshot.type)
          let msgList = [...this.data.msgList]
          if (snapshot.type === 'init') {
            msgList = [...snapshot.docs]
          } else {
            const currentMsg = snapshot.docChanges[0].doc
            if (this.data.roomStatus === 2 && currentMsg.content === this.data.word) {
              currentMsg.content = '猜中了！+3分'
              currentMsg.isAnswerRight = true
            }
            msgList.push(currentMsg)
          }
          this.setData({
            msgList
          })
        },
        onError: (err) => {
          console.error('the watch closed because of error', err)
        }
      })
      this.setData({
        msgWatcher
      })
    }
  }
})
